/*
 * Copyright @ 2024 weili23
 * com.example.mythread.a09threadExerciseRedEnvelope 16:43
 * All right reserved.
 */

package com.example.mythread.a09threadExerciseRedEnvelope;

import java.util.Random;

/**
 * @desc: 抢红包
 * @author: weili23
 * @createTime: 2024/10/21 16:43
 * @version: v1.0
 */
public class MyRedEnvelope implements Runnable{
    // 定义总金额
    static int money=100;
    //定义红包个数
    static int count = 3;
    //定义最小红包
    static final int MIN =1;
    @Override
    public void run() {
        synchronized (MyRedEnvelope.class){
            if(count ==0){
                System.out.println(Thread.currentThread().getName()+"没抢到红包");
            }else{
                int prize = 0;
                if (count==1){
                    //最后一次红包
                    prize = money;
                }else{
                    Random random = new Random();
                    // 确保至少留出2单位给后面两个部分
                    int bounds =money -(count-1)*MIN;
                    // 生成一个随机数
                    prize = random.nextInt(bounds);
                }
                money = money-  prize;
                count--;
                System.out.println(Thread.currentThread().getName()+"抢到了"+prize+"元");
            }
        }

    }
}
